package com.gxd.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * projectName:shopping
 * author:GuoXuDong
 * time:2022/4/18 0018 15:27
 * description:
 */

public class ServletBase extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("UTF-8");
//        String param = request.getParameter("method");
//        try {
//
//            Method method = this.getClass().getMethod(param, HttpServletRequest.class, HttpServletResponse.class);
//            Object result = method.invoke(this, request, response);
//
//            if(result==null){
//
//            }else {
//                String res = result.toString();
//                if(res.startsWith("redirect:")){
//                    String[] arr = res.split(":");
//                    if(arr!=null&&arr.length>1){
//                        response.sendRedirect(arr[1]);
//                    }
//
//                }else {
//                    String[] arr = res.split(":");
//                    if(arr!=null&&arr.length>1){
//                        request.getRequestDispatcher(arr[1]).forward(request,response);
//                    }
//
//                }
//
//
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println("调用方法失败");
//        }

        request.setCharacterEncoding("utf-8");
        String param = request.getParameter("method");
        try {
            Method method = this.getClass().getMethod(param, HttpServletRequest.class, HttpServletResponse.class);
            Object result = method.invoke(this, request, response);
            if(result==null){

            }else {
                String res = result.toString();
                if(res.startsWith("redirect:")){
                    String[] split = res.split(":");
                    if(split!=null&&split.length>1){

                        response.sendRedirect(split[1]);
                    }
                }else {
                    String[] split = res.split(":");
                    if(split!=null&&split.length>1){

                        request.getRequestDispatcher(split[1]).forward(request,response);
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用方法失败");
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}